﻿using PartsRetrospect.Business;
using PartsRetrospect.Comm;
using PartsRetrospect.Model;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PartsRetrospect.Forms
{
    public partial class FrmAirbagBarCodeEnter : UIPage
    {
        AirbagBLL airbagBLL = new AirbagBLL();
        List<UILight> LightList = new List<UILight>();
        bool isLoad = true;      //判断窗体是否首次加载

        public FrmAirbagBarCodeEnter()
        {
            InitializeComponent();
            string[] devices = new string[] { "扫码枪", "IO卡", "网络" };
            for (int i = 0; i < 3; i++)
            {
                UILight light = new UILight();
                light.Size = new System.Drawing.Size(25, 25);
                light.OnColor = Color.Green;
                light.OnCenterColor = Color.Green;
                light.OffColor = Color.Red;
                light.OffCenterColor = Color.Red;
                light.State = UILightState.Off;
                UILabel label = new UILabel();
                label.Text = devices[i];
                label.Height = 30;
                uiFlowLayoutPanel2.Add(light);
                uiFlowLayoutPanel2.Add(label);
                LightList.Add(light);
            }
            airbagBLL.Init();
        }

        private void FrmAirbagBarCodeEnter_Load(object sender, EventArgs e)
        {
            //如果窗体已经加载过则不重新加载
            if (!isLoad)
                return;
            isLoad = false;
            airbagBLL.OnAirbagBarDataChangeEvent += AirbagBarEvent;
            airbagBLL.OnCarBarDataChangeEvent += CarBarEvent;
            airbagBLL.MesgNotificationEvent += MesgShow;
            UpdateDeviceUI();
            GolbalVariable.DeviceStateChange.PropertyChanged += ConnectionEvent;

            DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
            dgvScanRecord.ClearSelection();
            dgvScanRecord.AutoGenerateColumns = false;
            dgvScanRecord.ReadOnly = true;
            dgvScanRecord.AddColumn("气囊位置", "Position");
            dgvScanRecord.AddColumn("气囊编码", "AirbagCode");
            dgvScanRecord.AddColumn("录入模式", "OperateModel");
            dgvScanRecord.AddColumn("录入时间", "CreateDate");
            btn.Name = "btnDelete";
            btn.HeaderText = "删除";
            btn.DefaultCellStyle.NullValue = "删除";
            dgvScanRecord.Columns.Add(btn);

            txtStation.Text = GolbalVariable.WorkShopSet.Position;
            txtWorkShopNo.Text = GolbalVariable.WorkShopSet.WorkShopNo.ToString();
            txtAirbagCount.Text = "0/0";

            PanelScanState.FillColor = Color.FromArgb(0, 192, 0);
            PanelScanState.Text = "扫描结束";
        }

        /// <summary>
        /// 车辆条码录入成功事件
        /// </summary>
        private void CarBarEvent()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                //刷新界面显示
                txtManyNo.Text = CarModel.ManyCode;
                txtBodyNo.Text = CarModel.BodyCode;
                txtVinCode.Text = CarModel.VinCode;
                txtScanTimeCar.Text = CarModel.ScanDate.ToString();
                txtCarType.Text = CarModel.CarType;
                txtAirbagCount.Text = CarModel.AirbagCount.ToString() + "/" + BarCodeConfigModel.barAirbagSubmitCount;

                txtManyNo.FillDisableColor = Color.White;
                txtManyNo.FillColor = Color.White;
                txtBodyNo.FillDisableColor = Color.White;
                txtBodyNo.FillColor = Color.White;
                txtVinCode.FillDisableColor = Color.White;
                txtVinCode.FillColor = Color.White;
                txtScanTimeCar.FillDisableColor = Color.White;
                txtScanTimeCar.FillColor = Color.White;
                txtCarType.FillDisableColor = Color.White;
                txtCarType.FillColor = Color.White;
                txtAirbagCount.FillDisableColor = Color.White;
                txtAirbagCount.FillColor = Color.White;

                if (GolbalVariable.UIAirbagList.Count() > 0)
                {
                    txtBodyNo.FillDisableColor = Color.LightGreen;
                    txtBodyNo.FillColor = Color.LightGreen;
                    txtVinCode.FillDisableColor = Color.LightGreen;
                    txtVinCode.FillColor = Color.LightGreen;
                    PanelScanState.FillColor = Color.Yellow;
                    PanelScanState.Text = "等待扫描";
                }
            }));
        }

        /// <summary>
        /// 气囊码录入成功事件
        /// </summary>
        private void AirbagBarEvent()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                dgvScanRecord.DataSource = null;
                dgvScanRecord.DataSource = GolbalVariable.UIAirbagList;
                dgvScanRecord.ClearSelection();
                //计算当前已确认的气囊数量
                CarModel.AirbagCount = GolbalVariable.UIAirbagList.Where(p => p.ScanCount >= GolbalVariable.WorkShopSet.ScanCount).Count();
                //更新界面显示当前确认的气囊数量
                txtAirbagCount.Text = CarModel.AirbagCount.ToString() + "/" + BarCodeConfigModel.barAirbagSubmitCount;
                FlowLayoutPanelChange();
                //扫码数量未达确认的数量为零时则判定当次扫码绑定完成，否则继续等待扫码
                if (GolbalVariable.UIAirbagList.Where(p => p.ScanCount < GolbalVariable.WorkShopSet.ScanCount).Count() <= 0)
                {
                    PanelScanState.FillColor = Color.FromArgb(0, 192, 0);
                    PanelScanState.Text = "扫描结束";
                }
                else
                {
                    PanelScanState.FillColor = Color.Yellow;
                    PanelScanState.Text = "等待扫描";
                }
            }));
        }

        private void ConnectionEvent(object sender, PropertyChangedEventArgs e)
        {
            UpdateDeviceUI();
        }

        /// <summary>
        /// 更新设备状态显示UI
        /// </summary>
        private void UpdateDeviceUI()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                if(GolbalVariable.DeviceStateChange.BarcodeScanner)
                    LightList[0].State = UILightState.On;
                else
                    LightList[0].State = UILightState.Off;
                if (GolbalVariable.DeviceStateChange.IoCar)
                    LightList[1].State = UILightState.On;
                else
                    LightList[1].State = UILightState.Off;
                if (GolbalVariable.DeviceStateChange.Sftp)
                    LightList[2].State = UILightState.On;
                else
                    LightList[2].State = UILightState.Off;
            }));
        }

        /// <summary>
        /// 实时消息显示
        /// </summary>
        /// <param name="mes">显示消息</param>
        /// <param name="index">消息类型(0错误信息；1正常信息)</param>
        private void MesgShow(string mes, int index)
        {
           this.Invoke(new MethodInvoker(() =>
            {
                if (index == 0 || index == -1)
                    AppendTextColorful(this.txtInfo, mes, Color.Red, true);
                else
                    AppendTextColorful(this.txtInfo, mes, Color.Green, true);
                if (string.IsNullOrEmpty(CarModel.VinCode) && index == 0)
                {
                    txtManyNo.FillDisableColor = Color.FromArgb(255, 128, 128);
                    txtManyNo.FillColor = Color.FromArgb(255, 128, 128);
                    txtBodyNo.FillDisableColor = Color.FromArgb(255, 128, 128);
                    txtBodyNo.FillColor = Color.FromArgb(255, 128, 128);
                    txtVinCode.FillDisableColor = Color.FromArgb(255, 128, 128);
                    txtVinCode.FillColor = Color.FromArgb(255, 128, 128);
                    txtScanTimeCar.FillDisableColor = Color.FromArgb(255, 128, 128);
                    txtScanTimeCar.FillColor = Color.FromArgb(255, 128, 128);
                    txtCarType.FillDisableColor = Color.FromArgb(255, 128, 128);
                    txtCarType.FillColor = Color.FromArgb(255, 128, 128);
                    txtAirbagCount.FillDisableColor = Color.FromArgb(255, 128, 128);
                    txtAirbagCount.FillColor = Color.FromArgb(255, 128, 128);
                }
            }));
        }

        /// <summary>
        /// 富文本框格式化方法
        /// </summary>
        /// <param name="rtBox">富文本框</param>
        /// <param name="addtext">添加文本内容</param>
        /// <param name="color">当前添加文本显示颜色</param>
        /// <param name="IsaddNewLine">是否换行</param>
        private void AppendTextColorful(UIRichTextBox rtBox, string addtext, Color color, bool IsaddNewLine)
        {
            if (IsaddNewLine)
            {
                addtext += Environment.NewLine;
            }
            rtBox.SelectionStart = rtBox.TextLength;
            rtBox.SelectionLength = 0;
            rtBox.SelectionColor = color;
            rtBox.AppendText(DateTime.Now.ToString() + "  " + addtext);
            rtBox.SelectionColor = rtBox.ForeColor;
            rtBox.Focus();
        }


        /// <summary>
        /// 输入条码
        /// </summary>
        /// <param name="barCode">条码</param>
        /// <param name="index">条码类型(1车辆条码；2气囊条码；)</param>
        /// <param name="airbagModel">修改气囊对象(新增时默认为空，修改时要传入气囊对象)</param>
        private void InputBarCode(string barCode = "", int index = 1, UIAirbagModel airbagModel = null)
        {
            UIEditOption option = new UIEditOption();
            option.AutoLabelWidth = true;
            if (index == 1)
                option.Text = "请输入长度为" + BarCodeConfigModel.barCarLength + "的条码";
            else
                option.Text = "请输入长度为" + BarCodeConfigModel.barAirbagL + "的条码";
            option.AddText("BarCode", "条码", barCode, true);
            UIEditForm frm = new UIEditForm(option);
            frm.ShowDialog();
            if (frm.IsOK)
            {
                string errMesg = "";
                barCode = frm["BarCode"].ToString();
                if (index == 1)
                {
                    if (!airbagBLL.CarBarEnter(barCode, false,ref errMesg))
                    {
                        UIMessageBox.ShowError(errMesg);
                        InputBarCode(barCode, index);
                    }
                }
                else
                {
                    if (!airbagBLL.AirbagBarEnter(barCode,  airbagModel, false, ref errMesg))
                    {
                        UIMessageBox.ShowError(errMesg);
                        InputBarCode(barCode, index);
                    }
                }
            }
        }

        private void FlowLayoutPanelChange()
        {
            uiFlowLayoutPanel1.Clear();
            foreach (var item in GolbalVariable.UIAirbagList)
            {
                UIPanel panel = new UIPanel();
                panel.Name = "panel" + item.Position + item.PositionId;
                panel.Text = item.Position;
                panel.Font = new Font("微软雅黑", 16);
                panel.Size = new System.Drawing.Size(130, 50);
                uiFlowLayoutPanel1.Add(panel);  
            }
            foreach (var item in GolbalVariable.UIAirbagList)
            {
                UIPanel panel = (UIPanel)GetControlInstance(uiFlowLayoutPanel1, "panel" + item.Position+ item.PositionId);
                if (item.IsWarn && item.ScanCount == 0)
                    panel.FillColor = Color.FromArgb(255, 128, 128);
                else if (item.ScanCount == 0)
                    panel.FillColor = Color.White;
                else if (item.ScanCount != 0 && item.ScanCount != GolbalVariable.WorkShopSet.ScanCount)
                    panel.FillColor = Color.Yellow;
                else if (item.ScanCount >= GolbalVariable.WorkShopSet.ScanCount)
                    panel.FillColor = Color.LightGreen;
            }
        }

        private void btnInputBarCode_Click(object sender, EventArgs e)
        {
            InputBarCode("", 1);
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            string errMesg = "";
            if(!airbagBLL.Save(ref errMesg))
            {
                airbagBLL.Clear();
                UIMessageBox.ShowError(errMesg);
            }          
        }

        private void btnAddAirbag_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(CarModel.VinCode))
            {
                UIMessageBox.ShowError("请先输入车辆条码!");
                return;
            }
            InputBarCode("", 2);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            airbagBLL.Clear();
        }

        private void btnUpdateAirbag_Click(object sender, EventArgs e)
        {
            if(dgvScanRecord.RowCount ==0)
            {
                UIMessageBox.ShowError("请先录入气囊信息!");
                return;
            }
            if(dgvScanRecord.CurrentRow != null)
            {
                var model = dgvScanRecord.CurrentRow.DataBoundItem as UIAirbagModel;
                InputBarCode("", 2, model);
            }else
            {
                UIMessageBox.ShowError("请先选择要修改的气囊数据!");
            }
        }
        private void btnStopAlarm_Click(object sender, EventArgs e)
        {
            airbagBLL.IoCardInitAction();
        }

        private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;
            var dgv = (UIDataGridView)sender;
            string buttonText = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].ToString();
            if (e.ColumnIndex == 4)
            {
               var model = dgv.Rows[e.RowIndex].DataBoundItem as UIAirbagModel;
                model.ScanCount = 0;
                model.AirbagCode = "";
                model.CreateDate = null;
                model.OperateModel = "";
                AirbagBarEvent();
            }
        }

        private void dgvScanRecord_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            var dgv = (UIDataGridView)sender;
            DataGridViewRow dgrSingle = dgv.Rows[e.RowIndex];
            var model = dgv.Rows[e.RowIndex].DataBoundItem as UIAirbagModel;
            if (model.IsWarn && model.ScanCount == 0)
                dgrSingle.DefaultCellStyle.BackColor = Color.FromArgb(255, 128, 128);
            else if (model.ScanCount == 0)
                dgrSingle.DefaultCellStyle.BackColor = Color.White;
            else if (model.ScanCount != 0 && model.ScanCount != GolbalVariable.WorkShopSet.ScanCount)
                dgrSingle.DefaultCellStyle.BackColor = Color.Yellow;
            else if (model.ScanCount >= GolbalVariable.WorkShopSet.ScanCount)
                dgrSingle.DefaultCellStyle.BackColor = Color.LightGreen;
        }

        /// <summary>
        /// 根据指定容器和控件名字，获得控件
        /// </summary>
        /// <param name="obj">容器</param>
        /// <param name="strControlName">控件名字</param>
        /// <returns>控件</returns>
        private object GetControlInstance(object obj, string strControlName)
        {
            IEnumerator Controls = null;//所有控件
            Control c = null;//当前控件
            Object cResult = null;//查找结果
            if (obj.GetType() == this.GetType())//窗体
            {
                Controls = this.Controls.GetEnumerator();
            }
            else//控件
            {
                Controls = ((Control)obj).Controls.GetEnumerator();
            }
            while (Controls.MoveNext())//遍历操作
            {
                c = (Control)Controls.Current;//当前控件
                if (c.HasChildren)//当前控件是个容器
                {
                    cResult = GetControlInstance(c, strControlName);//递归查找
                    if (cResult == null)//当前容器中没有，跳出，继续查找
                        continue;
                    else//找到控件，返回
                        return cResult;
                }
                else if (c.Name == strControlName)//不是容器，同时找到控件，返回
                {
                    return c;
                }
            }
            return null;//控件不存在
        }

        private void FrmAirbagBarCodeEnter_FormClosing(object sender, FormClosingEventArgs e)
        {
            airbagBLL.Close();
        }
    }
}
